package yo.latyoo.hokage.skmr.biz.service.email;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import yo.latyoo.hokage.skmr.biz.model.EmailModel;
import yo.latyoo.hokage.tools.consts.LogConst;
import yo.latyoo.hokage.tools.util.StringUtil;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService implements EmailProvider {
    private static Logger logger = LoggerFactory.getLogger(EmailService.class);

    private ThreadPoolExecutor emailThreadPool = new ThreadPoolExecutor(
            2,
            20,
            30L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(3000),
            r -> new Thread(r, "latyoo-job emailThreadPool-" + r.hashCode()),
            (r, executor) -> {
                r.run();
                logger.warn(LogConst.PREFIX + "latyoo-job email thread poll rejected handler(run now).");
            });

    @Resource
    MailProperties mailProperties;
    @Resource
    private JavaMailSender mailSender;
    @Override
    public void sendEmail(final EmailModel email) {
        emailThreadPool.execute(()->{
            sendSEmail(email);
        });
    }

    private void sendSEmail(EmailModel email){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailProperties.getUsername());
        message.setTo(email.getTo().split(";"));
        message.setSubject(email.getSubject());
        message.setText(email.getContent());
        if(!StringUtil.isNull(email.getCc()))
            message.setBcc(email.getCc().split(";"));
        mailSender.send(message);
    }
}
